﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSP.Dao.CommonDao;
using CSP.Dao.IObjectDaos.CSP;
using CSP.DataAccess;
using CSP.Model.CSP;

namespace CSP.Dao.ObjectDaos.CSP
{
    public class AddressDao : CSPCommonDao, IAddressDao
    {
        public AddressDao(CSPContext context, bool isTransaction = false)
            : base(context, isTransaction)
        {

        }

        public ICollection<Model.CSP.Address> FindAll()
        {
            throw new NotImplementedException();
        }

        public Model.CSP.Address GetDataById(int id)
        {
            return _context.Addresses.FirstOrDefault(a => a.Id == id);
        }

        public ICollection<Model.CSP.Address> FindByUser(string userName)
        {
            IQueryable<Address> result = _context.Addresses.Where(a => a.UserName == userName && a.Status==0);
            if (result.Count() == 0)
            {
                return null;
            }

            return result.ToArray();
        }

        public Model.CSP.Address GetByIdAndUser(int id, string userName)
        {
            return _context.Addresses.Include("Maps").FirstOrDefault(a => a.UserName == userName && a.Id == id);
        }

        public ICollection<Model.CSP.Address> GeDatatByIds(int[] Ids)
        {
            throw new NotImplementedException();
        }

        public void Add(Model.CSP.Address obj)
        {
            _context.Addresses.Add(obj);
            _context.SaveChanges();
        }

        public void Update(Model.CSP.Address obj)
        {
            _context.SaveChanges();
        }

        public Model.CSP.Address DeleteById(int id)
        {
            Address oldAddress = _context.Addresses.Include("Maps").FirstOrDefault(a => a.Id == id);
            if (oldAddress != null)
            {
                _context.Addresses.Remove(oldAddress);
            }
            else
            {
                oldAddress = null;
            }

            _context.SaveChanges();

            return oldAddress;
        }



        public Address DeleteByIdAndUser(int id, string userName)
        {
            Address oldAddress = _context.Addresses.Include("Maps").FirstOrDefault(a => a.Id == id && a.UserName == userName);
            if (oldAddress != null)
            {
                _context.Addresses.Remove(oldAddress);
            }
            else
            {
                oldAddress = null;
            }

            _context.SaveChanges();

            return oldAddress;
        }


    }
}
